package com.websuites.web.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("unchecked")
public class SpecialCharacterFilter implements Filter  
{
	private HashMap<String,String> mapURLPattern = new HashMap<String,String>();
	private String sCharacterPattern = "";
	
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException 
	{
		HttpServletRequest req = (HttpServletRequest) request;

		Enumeration enumParamName = request.getParameterNames();
		while (enumParamName.hasMoreElements()) 
		{
		    String sParamName = enumParamName.nextElement().toString();
	
		    String strParamvalues[] = request.getParameterValues(sParamName);
		    	
		    Pattern p = Pattern.compile(sCharacterPattern);
		    for (int i = 0; i < strParamvalues.length; i++) 
	        {
	    		Matcher matcher = p.matcher(strParamvalues[i]);
	    		
				if (matcher.matches())
				{				
					String sURI = req.getRequestURI().toString();
					String sContextPath = req.getContextPath();					
					String sShortURI = sURI.substring(sContextPath.length() + 1);

					Iterator itMap = mapURLPattern.entrySet().iterator();
					while (itMap.hasNext())
					{
						Map.Entry element = (Map.Entry)itMap.next();
						String sURLPattern = element.getKey().toString(); 
						
						Pattern p1 = Pattern.compile(sURLPattern);
						Matcher matcher1 = p1.matcher(sShortURI);
						
						if (matcher1.matches())
						{
							String sErrorURL = element.getValue().toString();
							((HttpServletResponse)response).sendRedirect(sContextPath + sErrorURL);
							return;
						}
					}
				}	
			}
		}
			
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException 
	{		
		Enumeration enumConfig = filterConfig.getInitParameterNames();
		while (enumConfig.hasMoreElements()) 
		{
			String sConfigName = enumConfig.nextElement().toString();
			String sConfigValue = filterConfig.getInitParameter(sConfigName);
			
			if (sConfigName.equals("Character"))
			{
				sCharacterPattern = sConfigValue;
			}
			else
			{
				sConfigName = sConfigName.replaceAll("\\*.", "[a-zA-Z0-9]+\\\\.");
				mapURLPattern.put(sConfigName, sConfigValue);
			}
		}		
	}

	public void destroy() 
	{
	}

}
